var $orderBtn;
var $itemList;
var $allCheckBtn;
var $selectedNum;
var $total;

function init() {
    $orderBtn = $("#orderBtn");
    $itemList = $("#itemList");
    $allCheckBtn = $('#allCheckBtn');
    $selectedNum = $('#selectedNum');
    $total = $('#total');
}

function initCart() {
    var itemList = [];
    mui.ajax($.constant.webRoot() + 'v1/cart', {
        type: 'GET',
        async: false,
        success: function (response) {
            if (response.code === 200) {
                itemList = response.data;
            }
        }
    });
    $itemList.empty();
    $.each(itemList, function (i, item) {

        var $li = $('<li class="mui-table-view-cell" style="padding: 0px;"></li>');
        var $rightBtn = $('<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>');
        var $itemBox = $('<div class="mui-input-row mui-checkbox mui-left mui-slider-handle" style="background-color: white"></div>');
        var $checkBox = $('<input name="productId" type="checkbox" data-productid="' + item.productId + '" style="top: 0.6rem; left: 0.4rem;" ' + (item.checked ? 'checked' : '') + '>');
        var $contentBox = $('<div style="padding-left: 1.3rem; width: 100%; float: left;padding-bottom: .2rem;"></div>');
        var $product = $('<div style="float: left"><img src="' + item.coverPicture + '" style="float: left; width: 2rem; ">' +
            '<div style="float: left; padding-top: 0.2rem;padding-left: 0.2rem;">' +
            '<div><span style="font-size: 0.4rem">' + item.name + '</span></div>' +
            '<div><span style="font-size: 0.35rem; color: #828282">' + item.description + '</span></div>' +
            '<div><span style="font-size: 0.35rem" name="price" data-price="' + item.price + '">NT$' + item.price + '</span></div></div></div>');
        var $numBox = $('<div style="float: right; padding-top: 0.7rem;"><div  id="' + 'numbox' + item.productId + '" class="mui-numbox"></div></div>');
        var $minusBtn = $('<button class="mui-btn mui-numbox-btn-minus" type="button">-</button>');
        var $numInput = $('<input class="mui-numbox-input" type="number" />');
        var $plusBtn = $('<button class="mui-btn mui-numbox-btn-plus" type="button">+</button>');

        $numBox.children('.mui-numbox').append($minusBtn, $numInput, $plusBtn);
        $contentBox.append($product, $numBox);
        $itemBox.append($checkBox, $contentBox);
        $li.append($itemBox, $rightBtn);
        $itemList.append($li);
        var numboxMU = mui('#numbox' + item.productId);
        numboxMU.numbox().setValue(item.num);
        initAllCheckBtn();
        initSelectedNum();
        initTotal();

        $product.click(function () {
            var url = '../product/index.html?id=' + item.productId;
            mui.openWindow(url, 'id');
        })

        $rightBtn.find('a').click(function () {
            mui.ajax($.constant.webRoot() + 'v1/cart/item', {
                type: 'DELETE',
                async: false,
                data: {
                    id: item.productId
                },
                success: function (response) {
                    if (response.code === 200) {
                        mui.toast('成功');
                        initCart();
                    }
                }
            });
        })

        $plusBtn.click(function () {
            var value = numboxMU.numbox().getValue();
            mui.ajax($.constant.webRoot() + 'v1/cart/item', {
                type: 'PUT',
                async: false,
                data: {
                    id: item.productId,
                    num: value
                },
                success: function (response) {
                    if (response.code === 200) {
                        initTotal()
                    }
                }
            });
        });

        $minusBtn.click(function () {
            var value = numboxMU.numbox().getValue();
            if (parseInt(value) < 1) {
                mui.toast('该宝贝不能减少哦');
                numboxMU.numbox().setValue(1);
                return;
            }
            mui.ajax($.constant.webRoot() + 'v1/cart/item', {
                type: 'PUT',
                async: false,
                data: {
                    id: item.productId,
                    num: value
                },
                success: function (response) {
                    if (response.code === 200) {
                        initTotal()
                    }
                }
            });
        });

        $checkBox.change(function () {
            var ischecked = $(this).prop("checked");
            var productid = $(this).data('productid');
            mui.ajax($.constant.webRoot() + 'v1/cart/item/' + (ischecked ? 'selected' : 'unSelected'), {
                type: 'PUT',
                async: false,
                data: {
                    ids: productid
                },
                success: function (response) {
                    initAllCheckBtn();
                    initSelectedNum();
                    initTotal();
                }
            });
        })
    })
}

function initTotal() {
    var total = 0;
    $itemList.find('li').each(function (i, item) {
        var productId = $(item).find('input[name="productId"]');
        if (!productId.prop("checked")) {
            return true;
        }
        var productid = productId.data('productid');
        var price = $(item).find('span[name="price"]').data('price');
        var numboxMU = mui('#numbox' + productid);
        var num = numboxMU.numbox().getValue();
        total += (price * num)
    });
    $total.text(total);
}

function initSelectedNum() {
    var num = 0;
    $itemList.find("input[name='productId']").each(function (i, item) {
        if ($(item).prop("checked")) {
            num++;
        }
    })
    $selectedNum.text("已選(" + num + ")");
}

function initAllCheckBtn() {
    $allCheckBtn.prop("checked", true);
    $itemList.find("input[name='productId']").each(function (i, item) {
        if (!$(item).prop("checked")) {
            $allCheckBtn.prop("checked", false);
            return false;
        }
    })

}

function initView() {
    initCart();
}

function initListener() {

    $orderBtn.bind('tap', function () {
        var selectFlag = false;
        $itemList.find('li').each(function (i, item) {
            var productId = $(item).find('input[name="productId"]');
            if (productId.prop("checked")) {
                selectFlag = true;
                return false;
            }
        });
        if(selectFlag){
            mui.openWindow('../orders/index.html', 'id');
        }else{
            mui.toast('沒有選購寶貝哦');
        }

    });
    $allCheckBtn.change(function () {
        var ischecked = $(this).prop("checked");
        $itemList.find("input[name='productId']").prop("checked", ischecked);

        var productIdList = [];
        $itemList.find("input[name='productId']").each(function (i, item) {
            productIdList.push($(item).data("productid"));
        });

        mui.ajax($.constant.webRoot() + 'v1/cart/item/' + (ischecked ? 'selected' : 'unSelected'), {
            type: 'PUT',
            async: false,
            data: {
                ids: productIdList.join('|')
            },
            success: function (response) {
                if (response.code === 200) {
                    initSelectedNum();
                    initTotal();
                }
            }
        });

    });
}

$(function () {
    init();
    initView();
    initListener();
});
